<?php
namespace App\Webdisk;
/**
 * 邮件发送器
 */
class MailSender{
    public $to;
    public $subject;
    public $content;

    /**
     * 构造函数
     * @param string $to 收件人地址
     * @param string $subject 标题
     * @param string $content 内容本体
     */
    public function __construct($to = '',$subject = '',$content = '')
    {
        $this->to=$to;
        $this->subject=$subject;
        $this->content=$content;
    }

    function to($to){
        $this->to=$to;
    }
    function setSubject($subject){
        $this->subject=$subject;
    }

    /**
     * 设置正文
     * @param string 正文
     */
    function setContent($content){
        $this->content=$content;
    }

    /**
     * 发送 走你
     * @return 无
     */
    function send(){
        $sockfd=socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
        if(socket_connect($sockfd,env("SMTP_ADDR"),25))
        {
            header("Content-Type:text/plain");
            // 问候服务器
            $msg="HELO ".env("SMTP_DOMAIN")."\r\n";
            socket_write($sockfd,$msg,strlen($msg));
            socket_read($sockfd,1024);

            // 请求验证
            $msg="AUTH LOGIN\r\n";
            socket_write($sockfd,$msg,strlen($msg));
            socket_read($sockfd,1024);

            // 验证-用户名
            $msg=env('SMTP_USER')."\r\n";
            socket_write($sockfd,$msg,strlen($msg));
            socket_read($sockfd,1024);

            // 验证-密码
            $msg=env('SMTP_PASSWD')."\r\n";
            socket_write($sockfd,$msg,strlen($msg));
            socket_read($sockfd,1024);

            // 请求准备发送邮件
            $msg="MAIL FROM:".env('SMTP_SENDER')."\r\n";
            socket_write($sockfd,$msg,strlen($msg));
            socket_read($sockfd,1024);

            // 设置收件人邮箱
            $msg="RCPT TO:<{$this->to}>\r\n";
            socket_write($sockfd,$msg,strlen($msg));
            socket_read($sockfd,1024);

            // 开始SMTP报文正文
            $msg="DATA\r\n";
            socket_write($sockfd,$msg,strlen($msg));
            socket_read($sockfd,1024);

            $msg="\r\n".$this->content;
            $msg="from:咸鱼云 ".env('SMTP_SENDER')."\r\nto:<{$this->to}>\r\nsubject:{$this->subject}\r\nContent-Type:text/html\r\n\r\n{$this->content}\r\n.\r\n";
            socket_write($sockfd,$msg,strlen($msg));
            socket_read($sockfd,1024);

            $msg="QUIT\r\n";
            socket_write($sockfd,$msg,strlen($msg));
            socket_read($sockfd,1024);
        }
    }
}

?>
